<template>
  <div name="词库" class="gl_contentBox gl_heightFull">
    <!-- 操作按钮 -->
    <el-row :gutter="20" class="gl_mb_15">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="openAddWordDialog('add')">增加词条</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" class="gl_table_noBorder" :border="false" stripe size="mini">
      <!-- 通用-序号 -->
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column prop="name" label="词条名称" align="center" />
      <el-table-column prop="name" label="词条类型" align="center">
        <template slot-scope="{row}">
          <div>{{ row.wordPoolType ? row.wordPoolType.name : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="genderCode" label="适用性别" align="center">
        <template slot-scope="{row}">
          <div>{{ row.genderCode === 'M' ? '男' : row.genderCode === 'W' ? '女' : '通用' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="词条内容" align="center">
        <template slot-scope="{row}">
          <el-popover
            placement="top-start"
            width="300"
            trigger="hover"
            :content="row.description"
          >
            <div slot="reference" style="width: 100%;cursor: pointer">{{ row.description.slice(0, 10) }}</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" label="创建人" align="center" />
      <el-table-column prop="creationTime" label="创建时间" align="center">
        <template slot-scope="{row}">
          <div>{{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="isEnabled" label="状态" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isEnabled"><i class="success_circle" />正常</div>
          <div v-else><i class="error_circle" />禁用</div>
        </template>
      </el-table-column>
      <el-table-column prop="operating" label="操作" align="center" width="200">
        <template slot-scope="{row,$index}">
          <el-button type="text" size="mini" @click="disableItem(row,$index)">{{ row.isEnabled ? '禁用' : '启用' }}</el-button>
          <el-button type="text" size="mini" @click="openAddWordDialog('edit', row)">编辑</el-button>
          <el-button type="text" size="mini" @click="deleteItem(row,$index)">
            <span class="gl_color_error">删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="qo.Page"
        :page-size="qo.MaxResultCount"
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>

    <!-- 增加词条弹窗 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="520px"
      :title="editType === 'add' ? '增加词条' : '编辑词条'"
      :visible.sync="addWordsDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <!-- :rules="addTemplate_Rules" -->
      <el-form
        ref="addWordsInputForm"
        :rules="AddWordInput_Rules"
        :model="addWordsInput"
        label-width="80px"
        size="mini"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="词条名称" prop="name">
              <el-input v-model.trim="addWordsInput.name" type="text" maxlength="10" show-word-limit placeholder="请输入词条名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="词条类型" prop="wordPoolTypeCode">
              <el-select v-model="addWordsInput.wordPoolTypeCode" size="mini" placeholder="词条类型" filterable style="width: 100%">
                <el-option v-for="item in dict.wordPoolType" :key="item.code" :value="item.code" :label="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="适用性别" prop="genderCode">
              <el-select v-model="addWordsInput.genderCode" size="mini" placeholder="适用性别" filterable style="width: 100%">
                <el-option v-for="item in genderList" :key="item.code" :value="item.code" :label="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="词条内容" prop="description">
              <el-input v-model.trim="addWordsInput.description" type="textarea" :rows="5" :min="0" maxlength="300" show-word-limit placeholder="请输入词条内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="addWordsDialog = false">取 消</el-button>
        <el-button size="mini" :loading="addDialogLoading" type="primary" @click="validateData">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import {
  api_POST_ClubWordPool, // 创建词库
  api_GET_ClubWordPool, // 获取词库列表
  api_GET_ClubWordPoolId, // 获取词库
  api_PUT_ClubWordPoolId, // 更新词库
  api_DELETE_ClubWordPoolId, // 删除词库
  api_PUT_ClubWordPoolIdEnableStatus // 更新启用状态
} from '@/extend/api/hallswaggerApi/app.js';
import { Api_GET_ClubWordPoolQO, CreateWordPoolInput } from '@/lib/form/hall/swaggerForm';
import { AddWordInput_Rules } from '@/lib/validate/hall/index.js';
export default {
  data () {
    return {
      qo: new Api_GET_ClubWordPoolQO(),
      tableData: [],
      loading: false,
      total: 0,
      // 新增词条
      addWordsDialog: false,
      addDialogLoading: false,
      addWordsInput: new CreateWordPoolInput(),
      AddWordInput_Rules: new AddWordInput_Rules(),
      editType: 'add'
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    }),
    genderList() {
      const _gender = (this.dict && this.dict.dictGender) || [];
      return [
        {
          value: '通用',
          code: 'X'
        },
        ..._gender
      ];
    }
  },
  watch: {
    addWordsDialog(val) {
      if (!val) {
        this.$refs['addWordsInputForm'].resetFields();
        this.addWordsInput = new CreateWordPoolInput();
      }
    }
  },
  created() {
    this.getDict();
    this.getPageList();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    getPageList(page) {
      this.qo.IsEnabled = null; // type: boolean
      this.qo.IncludeWordPoolType = true; // type: boolean
      this.qo.IncludeWordGender = null; // type: boolean
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      this.loading = true;
      api_GET_ClubWordPool(this.qo).then(
        res => {
          if (res) {
            this.tableData = res.items || [];
            this.total = res.totalCount;
            this.loading = false;
          }
        },
        error => {
          this.loading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 新建词条
    openAddWordDialog(type, row) {
      this.editType = type;
      if (row) {
        this.getWordsInfo(row);
      } else {
        this.addWordsDialog = true;
      }
    },
    getWordsInfo(row) {
      api_GET_ClubWordPoolId(row.id).then(
        res => {
          this.addWordsInput = res;
          this.addWordsDialog = true;
        },
        error => {
          this.addWordsDialog = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 确认
    validateData() {
      this.$refs['addWordsInputForm'].validate(valid => {
        if (valid) {
          if (this.editType === 'add') {
            this.addWords();
          } else {
            this.updateWords();
          }
        }
      });
    },
    addWords() {
      api_POST_ClubWordPool(this.addWordsInput).then(
        res => {
          this.$message({
            message: '创建成功',
            type: 'success'
          });
          this.getPageList();
          this.addWordsDialog = false;
        },
        error => {
          this.addWordsDialog = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    updateWords() {
      api_PUT_ClubWordPoolId(this.addWordsInput.id, this.addWordsInput).then(
        res => {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.getPageList();
          this.addWordsDialog = false;
        },
        error => {
          this.addWordsDialog = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 禁用
    disableItem(row, index) {
      api_PUT_ClubWordPoolIdEnableStatus(row.id, { enabled: !row.isEnabled }).then(
        res => {
          const _msg = res.isEnabled ? '启用成功' : '禁用成功';
          this.$message({
            message: _msg,
            type: 'success'
          });
          this.getPageList();
        },
        error => {
          this.addWordsDialog = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 删除
    deleteItem(row) {
      const _name = row.wordPoolType ? row.wordPoolType.name : '该词条';
      this.$confirm(`您确定要删除${_name}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubWordPoolId(row.id).then(
            () => {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getPageList();
            },
            error => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            }
          );
        });
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.qo.MaxResultCount = MaxResultCount;
      this.getPageList();
    },
    pageIndexChange(currentPage) {
      this.getPageList(currentPage);
    }
  }
};
</script>
<style scoped>
.success_circle {
  display: inline-block;
  margin-right: 8px;
  width: 6px;
  height: 6px;
  background: #14CE67;
  border-radius: 50%;
}
.error_circle {
  display: inline-block;
  margin-right: 8px;
  width: 6px;
  height: 6px;
  background: #FF3434;
  border-radius: 50%;
}
</style>

